package com.keyancompany.zhongbaopingtai.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.ConstansUrl;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.api.FileAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.EventBusEntity;
import com.keyancompany.zhongbaopingtai.model.User;
import com.keyancompany.zhongbaopingtai.utils.AppUtils;
import com.keyancompany.zhongbaopingtai.utils.FileHelper;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.weight.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;
import com.photoselector.util.CommonUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.BindString;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.keyancompany.zhongbaopingtai.api.FileAPI.UPLOAD_FILE;

/**
 * 我的资料
 * <p/>
 * Created by firefox on 2016/6/5.
 */
public class UserInforActivity extends BaseActivity {

    private static final int CHANGE_NAME_REQUEST = 221;
    private static final int CHANGE_SEX_REQUEST = 222;

    @BindString(R.string.my_info_text)
    String title;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.user_avatar)
    CircleImageView userAvatar;
    @Bind(R.id.introduction_value)
    TextView introductionValue;
    @Bind(R.id.introduction_parent)
    LinearLayout introductionParent;
    @Bind(R.id.user_info_name)
    TextView userInfoName;
    @Bind(R.id.user_info_nickName)
    TextView userInfoNickName;
    @Bind(R.id.user_info_area)
    TextView userInfoArea;
    @Bind(R.id.real_name_auther)
    TextView realNameAuther;
    @Bind(R.id.real_name_auther_parent)
    LinearLayout realNameAutherParent;
    @Bind(R.id.user_info_shanchang)
    TextView userInfoShanchang;

    @Bind(R.id.bind_phone_value)
    TextView phoneValue;

    @Bind(R.id.user_info_telenogly)
    TextView userInfoTelenogly;
    @Bind(R.id.weixin_account)
    TextView weixinAccount;
    @Bind(R.id.zhifubao_account)
    TextView zhifubaoAccount;
    @Bind(R.id.education)
    TextView education;
    @Bind(R.id.workat)
    TextView workat;
    @Bind(R.id.book_info)
    TextView bookInfo;
    @Bind(R.id.single_tag)
    TextView singleTag;
    @Bind(R.id.bind_phone_parent)
    LinearLayout bindPhoneParent;

    private String filePid, path;
    User user;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected int getMenuId() {
        return 0;
    }

    @Override
    protected void initToolBar() {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        initHomeAsUpEnable(toolbar);

    }

    @Override
    protected void setUpViews() {
        EventBus.getDefault().register(this);
        user = UserAPI.getCurrentUser();
        ImageLoader.getInstance().displayImage(user.getHeadpic(), userAvatar);
        userInfoNickName.setText(user.getUsername());
        if (TextUtils.isEmpty(user.getResume()))
            introductionValue.setText(getString(R.string.uninput_text));
        else
            introductionValue.setText(Html.fromHtml(user.getResume()));
        if (TextUtils.isEmpty(user.getAccountname()))
            userInfoName.setText(getString(R.string.unauthorized_text));
        else
            userInfoName.setText(user.getAccountname());
        userInfoArea.setText(user.getWorkat());

        if (TextUtils.isEmpty(user.getFiledsStr()))
            userInfoShanchang.setText(getString(R.string.uninput_text));
        else
            userInfoShanchang.setText(Html.fromHtml(user.getFiledsStr()));

        if (TextUtils.isEmpty(user.getPhone()))
            userInfoName.setText(getString(R.string.uninput_text));
        else
            userInfoName.setText(Html.fromHtml(user.getPhone()));

        if(!TextUtils.isEmpty(user.getWeixin())){
            weixinAccount.setText(user.getWeixin());
        }

        if(!TextUtils.isEmpty(user.getZhifubao())){
            zhifubaoAccount.setText(user.getZhifubao());
        }

        if(!TextUtils.isEmpty(user.getEducat())){
            education.setText(user.getEducat());
        }
        if(!TextUtils.isEmpty(user.getWorkat())){
            workat.setText(user.getWorkat());
        }
        if (TextUtils.isEmpty(user.getLabelsStr()))
            singleTag.setText(getString(R.string.uninput_text));
        else
            singleTag.setText(Html.fromHtml(user.getLabelsStr()));

//        userInfoTelenogly.setText(user.getSkills().toString());
    }

    @OnClick(R.id.user_avatar)
    public void chooseAvatar(View view) {
//        IntentUtils.startActivityForResult(this, PhotoSelectorActivity.class, Constants.SELECT_AVATAR);
        CommonUtils.launchActivityForResult(this,
                PhotoSelectorActivity.class, Constants.REQUESTCODE, 1);
    }

    @OnClick(R.id.real_name_auther_parent)
    public void toAutherInfo(View view) {
//        IntentUtils.startActivityForResult(this, PhotoSelectorActivity.class, Constants.SELECT_AVATAR);
        IntentUtils.startActivity(mContext, AutherInfoActivity.class);
    }

    @OnClick(R.id.user_info_name)
    public void editUserName(View view) {
//        EditUserInfoActivity.bundleIntent(this, EditUserInfoActivity.INTENT_USER_NAME, userInfoName.getText() == null ? "" : userInfoName.getText().toString());
    }

    @OnClick(R.id.user_info_nickName)
    public void editUserNick(View view) {
        EditUserInfoActivity.bundleIntent(this, EditUserInfoActivity.INTENT_USER_NICK, userInfoNickName.getText() == null ? "" : userInfoNickName.getText().toString());
    }

    @OnClick(R.id.bind_phone_parent)
    public void editAuthor(View view) {
        EditUserInfoActivity.bundleIntent(this, EditUserInfoActivity.INTENT_USER_NICK, userInfoNickName.getText() == null ? "" : userInfoNickName.getText().toString());
    }

    @OnClick(R.id.introduction_parent)
    public void editIntroduction(View view) {
        EditUserInfoActivity.bundleIntent(this, EditUserInfoActivity.INTENT_USER_INTRO, introductionValue.getText() == null ? "" : introductionValue.getText().toString());
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUESTCODE && resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                @SuppressWarnings("unchecked")
                List<PhotoModel> photos = (List<PhotoModel>) data.getExtras()
                        .getSerializable("photos");
                if (photos == null || photos.isEmpty())
                    return;
                StringBuffer sb = new StringBuffer();
                for (PhotoModel photo : photos) {
                    sb.append(photo.getOriginalPath());
                }
                CommonUtils.launchCropActivity(this, Constants.CROPCODE,
                        sb.toString());
            }
        } else if (requestCode == Constants.CROPCODE && resultCode == RESULT_OK) {
            if (data == null)
                return;
            filePid = null;
            // 拿到剪切数据
            final Bitmap bmap = data.getParcelableExtra("data");
            Message msg = new Message();
            msg.obj = bmap;
            msg.what = 1;
            handler.sendMessage(msg);
            File cropFile = FileHelper.saveAvatarBitmap(AppUtils.compressScale(bmap));
            if (cropFile != null) {
                FileAPI.uploadFile(cropFile, this, getLoading(-1));
            }

        } else if (requestCode == CHANGE_NAME_REQUEST
                && resultCode == RESULT_OK)

        {
//            name.setText(data.getDataString());
        } else if (requestCode == CHANGE_SEX_REQUEST && resultCode == RESULT_OK)

        {
//            sex.setText(data.getDataString());
        }
    }

    /**
     * 使用onEventMainThread来接收事件，那么不论分发事件在哪个线程运行，接收事件永远在UI线程执行
     * 可以用来更新UI
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBusEntity event) {
        switch (event.getType()) {
//            case EventBusEntity.Type.HEAD:
//                ImageLoader.getInstance().displayImage(ConstansUrl.HOST + user.getHeadpic(), userAvatar);
//                break;
            case EventBusEntity.Type.USERNAME:
                userInfoNickName.setText(user.getUsername());
                break;
            case EventBusEntity.Type.USERDISC:
                if (TextUtils.isEmpty(user.getResume()))
                    introductionValue.setText(getString(R.string.uninput_text));
                else
                    introductionValue.setText(user.getResume());
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if (msg.what == 1) {
                Bitmap map = (Bitmap) msg.obj;
                userAvatar.setImageBitmap(map);
            }
        }
    };

    @Override
    public void failed(String error) {
        super.failed(error);
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);
        BaseModel base = JSONObject.parseObject(json, BaseModel.class);

        if (base.isSuccess()) {
            //{"result":"sucess","token":"111111","data":{"pid":"4028808b586080b901586090a8730000",
            // "path":"/upload/699d892b-c082-440e-afbe-057f80d60bd3.png",
            // "name":"1471923710054.png","createuser":"10086","createtime":"2016-11-14 10:00:42"},"msg":"上传成功"}
            if (type == UPLOAD_FILE) {
                JSONObject item = JSONObject.parseObject(base.data);
                filePid = item.getString("pid");
                path = item.getString("path");
                UserAPI.updateHeadPic(filePid, UserInforActivity.this, getLoading(-1));
            } else if (type == UserAPI.EDIT_USER_INFO) {
                user.setHeadpic(ConstansUrl.HOST + path);
                ImageLoader.getInstance().displayImage(user.getHeadpic(), userAvatar);
                EventBus.getDefault().post(new EventBusEntity(EventBusEntity.Type.HEAD));
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
